package com.chen.system.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.result.Result;
import com.chen.common.utils.MD5;
import com.chen.model.system.SysUser;
import com.chen.model.vo.SysUserQueryVo;
import com.chen.system.annotation.Log;
import com.chen.system.enums.BusinessType;
import com.chen.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Y·C
 * @since 2023-04-04
 */

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;


    @Log(title = "更改用户状态",businessType = BusinessType.INSERT)
    @ApiOperation("更改用户状态")
    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Integer id,@PathVariable Integer status){
        sysUserService.updateStatus(id,status);
        return Result.ok();
    }


    @ApiOperation("用户列表")
    @GetMapping("/{page}/{limit}")
    public Result list(@PathVariable Integer page, @PathVariable Integer limit,
                       SysUserQueryVo sysUserQueryVo){
        //创建page对象
        Page<SysUser> pageParam = new Page<>(page, limit);
        //调用service方法
        IPage<SysUser> pageModel = sysUserService.selectPage(pageParam,sysUserQueryVo);

        return Result.ok(pageModel);
    }

    @Log(title = "添加用户",businessType = BusinessType.INSERT)
    @ApiOperation("添加用户")
    @PostMapping("save")
    public Result save(@RequestBody SysUser user){
        //把输入的密码进行加密 md5
        String encrypt = MD5.encrypt(user.getPassword());
        user.setPassword(encrypt);
        if (sysUserService.save(user)) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @ApiOperation("根据id查询")
    @PostMapping("getUser/{id}")
    public Result getUser(@PathVariable Integer id){
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);
    }

    @Log(title = "修改用户",businessType = BusinessType.UPDATE)
    @ApiOperation("修改用户")
    @PostMapping("update")
    public Result update(@RequestBody SysUser user){

        if (sysUserService.updateById(user)) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @Log(title = "删除用户",businessType = BusinessType.DELETE)
    @ApiOperation("删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Integer id){
        if (sysUserService.removeById(id)) {
            return Result.ok();
        }else {
            return Result.fail();
        }
    }



}

